package su.camunda.operate.plugin;

import java.util.List;

import org.camunda.bpm.engine.impl.cfg.AbstractProcessEnginePlugin;
import org.camunda.bpm.engine.impl.cfg.ProcessEngineConfigurationImpl;
import org.camunda.bpm.engine.impl.history.event.HistoricVariableUpdateEventEntity;
import org.camunda.bpm.engine.impl.history.event.HistoryEvent;
import org.camunda.bpm.engine.impl.history.handler.HistoryEventHandler;
import org.springframework.stereotype.Component;

import lombok.extern.slf4j.Slf4j;

@Component
@Slf4j
public class VariableUpdatePlugin extends AbstractProcessEnginePlugin {

    @Override
    public void preInit(ProcessEngineConfigurationImpl processEngineConfiguration) {
        HistoryEventHandler oldHistoryEventHandler = processEngineConfiguration.getHistoryEventHandler();
        
        processEngineConfiguration.setHistoryEventHandler(new HistoryEventHandler() {
            @Override
            public void handleEvent(HistoryEvent historyEvent) {
                if (historyEvent instanceof HistoricVariableUpdateEventEntity) {
                    HistoricVariableUpdateEventEntity variableEvent = (HistoricVariableUpdateEventEntity) historyEvent;
                    String executionId = variableEvent.getExecutionId();
                    String processInstanceId = variableEvent.getProcessInstanceId();
                    String taskId = variableEvent.getTaskId();
                    // 在这里实现你的自定义逻辑
                }

                if (oldHistoryEventHandler != null) {
                    oldHistoryEventHandler.handleEvent(historyEvent);
                }

            }

            @Override
            public void handleEvents(List<HistoryEvent> historyEvents) {
                for (HistoryEvent historyEvent : historyEvents) {
                    handleEvent(historyEvent);
                }
            }
        });
    }
}
